<template>
  <div class="app-container">
    <el-dialog title="配置门店权益" :visible.sync="visible" width="800px" v-if="visible" append-to-body
      :close-on-click-modal="false" @close="closeDialog">
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" :label-width="labelWidth" :disabled="disabled">
        <el-steps :active="active" finish-status="success" simple>
          <el-step title="选择门店"></el-step>
          <el-step title="配置权益"></el-step>
        </el-steps>
        <div class="from_box">
          <template v-if="active==0">
            <el-form-item label="选择门店" prop="shopList">
              <el-select filterable v-model="ruleForm.shopList" multiple placeholder="请选择" @change="shopChange"
                style="width: 300px">
                <el-option v-for="item in options" :key="item.shopId" :label="item.shopName" :value="item.shopId">
                </el-option>
              </el-select>
              <div class="select_shop" v-if="selectItems.length!=0">
                <span>已选门店：</span>
                <span v-for="(item,indexs) in selectItems" :key="indexs">
                  {{item.shopName}}
                  <span v-if="selectItems.length!=indexs+1">，</span>
                </span>
              </div>
            </el-form-item>
          </template>
          <template v-if="active==1||active==2">
            <div v-for="(item,aIndex) in stepTwoLs" :key="aIndex">
              <div class="shop_name">门店{{aIndex+1}}：{{item.shopName}}</div>
              <el-form-item :label="'配置用户'+nav.levelName+'权益'" required v-for="(nav,bIndex) in item.setupList"
                :key="bIndex">
                <el-radio-group v-model="nav.equityType" class="el_radio_box">
                  <el-radio :label="'1'">无权益</el-radio>
                  <el-radio :label="'2'">
                    <span>单笔订单满</span>
                    <el-input class="input_box" :disabled="nav.equityType=='2'?false:true" v-model="nav.reduceNum1"
                      placeholder="请输入" :style="{width: inputWidth}" @input="inputClick">
                    </el-input>
                    <span>减</span>
                    <el-input class="input_box" :disabled="nav.equityType=='2'?false:true" v-model="nav.reduceNum2"
                      placeholder="请输入" :style="{width: inputWidth}" @input="inputClick">
                    </el-input>
                    <span>元</span>
                  </el-radio>
                  <el-radio :label="'3'">
                    <span>单笔订单打</span>
                    <el-input class="input_box" :disabled="nav.equityType=='3'?false:true" v-model="nav.discountNum1"
                      placeholder="请输入" :style="{width: inputWidth}" @input="inputClick">
                    </el-input>
                    <span>折，上限折扣</span>
                    <el-input class="input_box" :disabled="nav.equityType=='3'?false:true" v-model="nav.discountNum2"
                      placeholder="请输入" :style="{width: inputWidth}" @input="inputClick">
                    </el-input>
                    <span>元</span>
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </div>
          </template>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="nextStep('ruleForm')" v-if="active==0">下一步</el-button>
        <el-button type="primary" @click="active=0" v-if="active==1||active==2">上一步</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')" v-if="active==1||active==2">保存</el-button>
        <el-button @click="cancel" v-if="!disabled">取 消</el-button>
        <el-button @click="cancel" v-if="disabled">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    shopList,
    equityCardShopSetup,
    changeSetup
  } from "@/api/equityManager/equityCard";

  export default {
    props: { //排除门店id
      shopIdList: {
        type: Array, //
        default: [] // 默认值
      }
    },
    name: "Dialog",
    data() {
      return {
        labelWidth: '130px',
        inputWidth: '100px',
        //已选门店
        selectItems: [],
        //数字权益卡id
        cardId: '',
        // 是否禁用表单
        disabled: false,
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        visible: false,
        //步骤
        active: 0,
        // 店铺数组
        options: [],
        stepTwoLs: [], //配置权益数组
        fromList: [], //提交表单
        // 表单参数
        ruleForm: {
          shopList: [],
        },
        // 表单校验
        rules: {
          shopList: [{
            required: true,
            message: "请选择店铺",
            trigger: ['blur', 'change'],
          }],
        }
      };
    },
    created() {

    },
    methods: {
      /** 打开数字权益卡列表弹框 */
      open(id, disabled) {
        this.disabled = disabled
        this.getShopList()
        console.log('this.shopIdList+', this.shopIdList)
        if (id) {
          // getEquityCard(id).then(response => {
          //   this.form = response.data;
          // });
        }
        this.visible = true
      },
      /** 获取权益门店选择列表 */
      getShopList() {
        let data = {
          shopIdList: this.shopIdList,
        }
        shopList(data).then(response => {
          this.options = response.data;
        });
      },
      shopChange(e) { //店铺名称选择
        console.log(e)
        this.selectItems = []
        this.selectItems = this.options.filter(item => e.indexOf(item.shopId) >= 0)
        // console.log(this.ruleForm.shopList)
      },
      /** 获取数字权益卡门店设置列表 */
      getEquityCardShopSetup() {
        let data = {
          shopIdList: this.ruleForm.shopList,
          cardId: this.cardId,
        }
        equityCardShopSetup(data).then(response => {
          this.active = 1
          this.stepTwoLs = response.data;
          this.stepTwoLs.forEach(item => {
            item.setupList.forEach(nav => {
              if (nav.equityType == '2') {
                nav.reduceNum1 = nav.discountLimit
                nav.reduceNum2 = nav.discountMoney
              } else if (nav.equityType == '3') {
                nav.discountNum1 = nav.discountLimit
                nav.discountNum2 = nav.discountMoney
              } else {
                nav.reduceNum1 = ''
                nav.reduceNum2 = ''
                nav.discountNum1 = ''
                nav.discountNum2 = ''
              }
            })
          })

          // console.log(this.stepTwoLs)
        });
      },
      inputClick() { //修复input无法输入问题
        this.$forceUpdate()
      },
      /** 重置表单 */
      reset() {
        console.log('取消')
        this.$refs['ruleForm'].resetFields()
        this.ruleForm.shopList = []
        this.selectItems = []
        this.stepTwoLs = []
        this.active = 0
      },
      // 取消按钮
      cancel() {
        this.visible = false;
        this.reset()
      },
      closeDialog() { //关闭弹窗
        this.reset()
      },
      /** 下一步 */
      nextStep(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            // alert('submit!');
            console.log(this.ruleForm)
            // this.active = 1
            this.getEquityCardShopSetup()
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      /** 提交按钮 */
      submitForm(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            let isTrue1 = true
            let isTrue2 = true
            let isTrue3 = true
            this.fromList = this.stepTwoLs
            this.fromList.forEach(item => {
              item.setupList.forEach(nav => {
                if (nav.equityType == '2') {
                  nav.discountLimit = nav.reduceNum1
                  nav.discountMoney = nav.reduceNum2
                  isTrue2 = this.check(2, nav.reduceNum1, nav.reduceNum2)
                } else if (nav.equityType == '3') {
                  nav.discountLimit = nav.discountNum1
                  nav.discountMoney = nav.discountNum2
                  isTrue3 = this.check(3, nav.discountNum1, nav.discountNum2)
                } else if (nav.equityType == '1') {
                  nav.reduceNum1 = ''
                  nav.reduceNum2 = ''
                  nav.discountNum1 = ''
                  nav.discountNum2 = ''
                  isTrue1 = this.check(1, nav.reduceNum1, nav.reduceNum2)
                }
              })
            })
            // console.log(this.fromList)
            // console.log(isTrue1, isTrue2, isTrue3)
            // 转换门店设置为列表格式
            if (isTrue1 && isTrue2 && isTrue3) {
              this.$emit('getLs', this.fromList, 1)
              this.active = 2
              this.cancel();
            }

            // // 打开遮罩层
            // this.$modal.loading("正在处理中数据，请稍后...");
            // if (this.form.id != null) {
            //   updateEquityCard(this.form).then(response => {
            //     this.$modal.msgSuccess("修改成功");
            //     this.cancel();
            //     this.$emit('refresh')
            //   }).finally(() => {
            //     // 关闭遮罩层
            //     this.$modal.closeLoading();
            //   });
            // } else {
            //   addEquityCard(this.form).then(response => {
            //     this.$modal.msgSuccess("新增成功");
            //     this.cancel();
            //     this.$emit('refresh')
            //   }).finally(() => {
            //     // 关闭遮罩层
            //     this.$modal.closeLoading();
            //   });
            // }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      /** 表单检查提交 */
      check(type, num1, num2) {
        console.log(type, num1, num2)
        let regex = /^((0.[1-9]{1})|(([1-9]{1})(.\d{1})?))$/
        // let numRegex = /^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*))$/
        var numRegex = /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/;
        if (type == 2 && (num1 == '' || num1 == undefined)) {
          this.$message.error('请输入满减金额条件');
          return false
        } else if (type == 2 && (num2 == '' || num2 == undefined)) {
          this.$message.error('请输入满减金额');
          return false
        } else if (type == 2 && Number(num1) <= Number(num2)) {
          this.$message.error('满减金额不能大于满减金额条件');
          return false
        } else if (type == 3 && (num1 == '' || num1 == undefined)) {
          this.$message.error('请输入折扣');
          return false
        } else if (type == 3 && regex.test(num1) == false) {
          this.$message.error('请输入正确折扣');
          return false
        } else if ((!numRegex.test(num1) || !numRegex.test(num2)) && num1 != '' && num2 != '' && num1 != undefined &&
          num2 != undefined) {
          this.$message.error('请输入正确数值');
          return false
        } else {
          return true
        }
      },
    }
  };

</script>
<style scoped>
  .from_box {
    margin: 20px 0 0;
  }

  .shop_name {
    font-weight: bold;
    font-size: 16px;
    color: #1890FF;
    margin-bottom: 30px;
  }

  .input_box {
    margin: 0 10px;
  }

  .el_radio_box {
    display: flex;
    flex-direction: column;
  }

  .el_radio_box .el-radio {
    margin-top: 12px;
  }

</style>
